#import "Controller.h"

#import "FolderModel.h"
#import "PhotoBrowser.h"
#import "PhotoSlideShow.h"
#import "PhotoViewer.h"
#import "Preferences.h"
#import "PreferencesData.h"
#import "Epeg.h"
#import "ExifController.h"
#import "IRController.h"
#import "ShiftExifController.h"
#import "SlideshowManager.h"
#import "SlideshowModel.h"
#import "ThumbData.h"
#import "Utility.h"
#import <sys/time.h>


#import "QTKit/QTKit.h"


#define TO_TRASH_SOUND		@"/System/Library/Components/CoreAudio.component/" \
							"Contents/Resources/SystemSounds/dock/drag to trash.aif"


#define NEW_FOLDER_NAME	@"untitled folder"


#define PREF_BROWSER_FRAME_RECT		@"Browser.frameRect"


static Controller	*controller = nil;

static NSArray		*fileTypes;
static NSArray		*imageTypes;
static NSArray		*movieTypes;


@implementation Controller

//------------------------------------------------------------------------------
+ (Controller*) sharedController
{
	if (nil == controller)
	{
		NSLog(@"instantiating controller");
		controller = [[Controller alloc] init];
		[controller awakeFromNib];
	}

	return controller;
}

//------------------------------------------------------------------------------
+ (int) mediaTypeForFile:(NSString*) file
{
	int mediaType = MEDIA_TYPE_UNKNOWN;
	if (nil != file)
	{
		NSString *extension = [[file pathExtension] lowercaseString];
		if (nil != extension)
		{
			if (NSNotFound != [imageTypes indexOfObject: extension])
			{
				mediaType = MEDIA_TYPE_IMAGE;
			}
			else
			if (NSNotFound != [movieTypes indexOfObject: extension])
			{
				mediaType = MEDIA_TYPE_MOVIE;
			}
		}
	}

	return mediaType;
}

//------------------------------------------------------------------------------
- (void) applicationWillTerminate:(NSNotification *)notification
{
	// If any browsers, get the first one to close up so its preferences are saved.
	if ([browsers count])
	{
		[[[browsers objectAtIndex: 0] mainWindow] performClose: nil];
	}

	// And if any viewers are open, close the first one as well.
	if ([viewers count])
	{
		[[[viewers objectAtIndex: 0] mainWindow] performClose: nil];
	}

	// And if any slideshows are open, close the first one as well.
	if ([slideshows count])
	{
		[[[slideshows objectAtIndex: 0] mainWindow] performClose: nil];
	}

	// If the Slideshow Manager is open, close it, too.
	if (nil != ssManager)
	{
		[[ssManager mainWindow] performClose: nil];
	}

	// And persist the preferences to disk
	[prefsData writeToDefaults: userPreferences];
	[userPreferences synchronize];
}

//------------------------------------------------------------------------------
- (BOOL) application
	: (NSApplication*) app 
	openFile: (NSString*) filename
{
	NSFileManager *fileman = [NSFileManager defaultManager];
	BOOL isDir;
	if (YES == [fileman fileExistsAtPath: filename  isDirectory:&isDir])
	{
		if (YES == isDir)
		{
			PhotoBrowser *pb = [self getOrCreateBrowser];
			[pb loadDirectoryAndSelect: filename  parentDir:nil];
		}
		else
		if (NO == isDir)
		{
			if ([self isSlideshowFile: filename])
			{
				[self openSlideshowFile: filename];
			}
			else
			if ([self isSupportedFile: filename])
			{
				[self openImageInViewer: filename];
			}
			else
			{
				NSString *msg = NSLocalizedString(@"Unsupported file \"%@\"", @"openUnsupportedMsg");
				NSRunAlertPanel(
					NSLocalizedString(@"Unsupported file", @"openUnsupportedTitle"),
					[NSString stringWithFormat: msg, filename],
					NSLocalizedString(@"OK", @"OK"),
					nil,
					nil);
			}
		}
	}
	else
	{
		NSString *msg = NSLocalizedString(@"Cannot find the file \"%@\"", @"openFailedMsg");
		NSRunAlertPanel(
			NSLocalizedString(@"Cannot find file", @"openFailedTitle"),
			[NSString stringWithFormat: msg, filename],
			NSLocalizedString(@"OK", @"OK"),
			nil,
			nil);
	}

	return YES;
}

//------------------------------------------------------------------------------
- (void) awakeFromNib
{
	long systemVersion;
	OSErr err = Gestalt(gestaltSystemVersion, &systemVersion);
	if (err != noErr || ((systemVersion & 0x0000FFF0) < 0x1030))
	{
		NSRunAlertPanel(
			NSLocalizedString(@"Cannot run GoFoto", @"requiresPantherTitle"),
			NSLocalizedString(@"GoFoto requires OS X 10.3 (Panther) or higher.", "requiresPanther"),
			NSLocalizedString(@"Exit", @"Exit"),
			nil,
			nil);
		[[NSApplication sharedApplication] terminate: nil];
	}

	controller = self;
	[NSApp setDelegate: self];

	NSArray *movieTypes = [QTMovie movieFileTypes: QTIncludeCommonTypes];
	[movieTypes retain];

	imageTypes = [NSImage imageFileTypes];
	[imageTypes retain];

	NSMutableArray *types = [[NSMutableArray alloc] initWithArray: movieTypes];
	[types addObjectsFromArray: imageTypes];
	fileTypes = types;

	browsers = [NSMutableArray arrayWithCapacity: 0];
	[browsers retain];
	viewers = [NSMutableArray arrayWithCapacity: 0];
	[viewers retain];
	slideshows = [NSMutableArray arrayWithCapacity: 0];
	[slideshows retain];

	soundToTrash = [[NSSound alloc] initWithContentsOfFile
		: TO_TRASH_SOUND
		byReference: YES];

	userPreferences = [[NSUserDefaults standardUserDefaults] retain];
	prefsData = [[PreferencesData alloc] initWithDefaults: userPreferences];
	[IRController sharedController]; 

	srandomdev();

	// Post an event - when it's executed, we'll be able to determine if we have
	// opened a browser/viewer already or if we need to.
	[self
		performSelectorOnMainThread: @selector(postAwakeFromNib:)
		withObject: nil
		waitUntilDone: NO];
}

//------------------------------------------------------------------------------
- (void) postAwakeFromNib:(id) value
{
	if (0 == [browsers count] && 0 == [viewers count])
	{
		PreferencesData *pd = [self preferencesData];

		NSString *path = GetPicturesFolder();
		if (STARTUP_FOLDER_LAST == [pd startupFolderType])
		{
			NSString *lastFolder = [[self userPreferences] stringForKey: PREF_KEY_LAST_FOLDER];
			if (nil != lastFolder)
			{
				path = lastFolder;
			}
		}
		else
		{
			path = [pd startupFolder];
		}

		NSFileManager *manager = [NSFileManager defaultManager];
		BOOL isDir;
		if (NO == [manager fileExistsAtPath:path isDirectory:&isDir] || NO == isDir)
		{
			path = GetPicturesFolder();
		}

		if (STARTUP_WIN_BROWSER == [pd startupWindowType])
		{
			PhotoBrowser *pb = [self getOrCreateBrowser];
			[pb loadDirectoryAndSelect: path  parentDir:nil];
		}
		else
		{
			[self openImageInViewer: path];
		}
	}
}

//------------------------------------------------------------------------------
// Actions
//------------------------------------------------------------------------------
- (IBAction) browseFolder:(id)sender
{
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	[openPanel setCanChooseFiles:YES];
	[openPanel setCanChooseDirectories:YES];

	NSString *dir = [[self activeBrowserOrViewer] currentFolder];
	if (nil == dir)
	{
		dir = GetPicturesFolder();
	}

	int retCode = [openPanel runModalForDirectory
		: dir
		file:nil 
		types:nil];

	if (NSOKButton == retCode)
	{
		NSString *newPath = [openPanel filename];
		[self application:NSApp  openFile:newPath];
	}
}

//------------------------------------------------------------------------------
- (IBAction) newWindow:(id)sender
{
	[self createBrowser];
}

//------------------------------------------------------------------------------
- (IBAction) newViewerWindow:(id)sender
{
	[self createViewer];
}

//------------------------------------------------------------------------------
- (IBAction) preferences:(id)sender
{
	Preferences *prefDialog = [[Preferences alloc] initWithPrefs: prefsData];
	[NSBundle loadNibNamed:@"Preferences"  owner:prefDialog];
	NSWindow *prefWindow = [prefDialog mainWindow];
	[prefWindow makeKeyAndOrderFront: prefWindow];
}

//------------------------------------------------------------------------------
// Public helpers
//------------------------------------------------------------------------------
- (void) revealInFinder:(NSString*) file
{
	NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
	[workspace selectFile: file  inFileViewerRootedAtPath: @""];
}

//------------------------------------------------------------------------------
- (void) showInfoDialog:(ExifController**) pexifDialog  file:(NSString*) file
{
	if (nil == *pexifDialog)
	{
		*pexifDialog = [[ExifController alloc] init];
		[NSBundle loadNibNamed:@"ExifDialog"  owner:*pexifDialog];
	}

	[*pexifDialog setFile: file];
	[[*pexifDialog mainWindow] makeKeyAndOrderFront: [*pexifDialog mainWindow]];
}

//------------------------------------------------------------------------------
- (void) shiftHelper:(NSArray*) tdList  exif:(BOOL)exif
{
	NSDate *date = [[tdList objectAtIndex: 0] date];
	if (NO == exif)
	{
		date = [[tdList objectAtIndex: 0] fileDate];
	}

	NSString *note;
	if (1 == [tdList count])
	{
		note = [[tdList objectAtIndex: 0] name];
	}
	else
	{
		NSString *msg;
		if (YES == exif)
		{
			msg = NSLocalizedString(@"(%d files selected)", @"shiftExifDate.selected");
		}
		else
		{
			msg = NSLocalizedString(@"(%d files selected)", @"shiftFileDate.selected");
		}

		note = [NSString stringWithFormat: msg, [tdList count]]; 
	}

	ShiftExifController *dialog = [[ShiftExifController alloc] initWithDate: date  note: note  exif:exif];
	[NSBundle loadNibNamed:@"ShiftExif"  owner:dialog];
	NSWindow *dlgWindow = [dialog mainWindow];
	if (NSRunStoppedResponse == [NSApp runModalForWindow: dlgWindow])
	{
		NSMutableArray *failed = [[NSMutableArray alloc] init];

		NSFileManager *fileManager = [NSFileManager defaultManager];
		long delta = [dialog delta];
		BOOL updateFileDate = [dialog updateFileDate];

		int count = [tdList count];
		int idx;
		for (idx = 0; idx < count; ++idx)
		{
			NSDate *newDate = nil;
			ThumbData *td = [tdList objectAtIndex: idx];
			if (NO == exif || YES == setExifDates([td fullPath], delta, &newDate))
			{
				if (YES == exif)
				{
					[td setExifDate: newDate];
				}

				if (NO == exif || YES == updateFileDate)
				{
					NSDictionary *oldAttrs = [fileManager fileAttributesAtPath: [td fullPath] traverseLink: NO];
					NSMutableDictionary *newAttrs = [NSMutableDictionary dictionaryWithDictionary: oldAttrs];

					NSDate *fileDate;
					if (YES == exif)
					{
						fileDate = newDate;
					}
					else
					{
						fileDate = [[NSDate alloc] initWithTimeInterval: delta   sinceDate: date];
					}

					[td setFileDate: fileDate];

					[newAttrs setValue:fileDate  forKey:NSFileCreationDate];
					[newAttrs setValue:fileDate  forKey:NSFileModificationDate];
					[fileManager changeFileAttributes:newAttrs  atPath:[td fullPath]];
				}
			}
			else
			{
				[failed addObject: td];
			}
		}

		int countFailed = [failed count];
		if (countFailed > 0)
		{
			NSString *title;
			if (1 == countFailed)
			{
				if (YES == exif)
				{
					title = NSLocalizedString(@"ShiftExif failed on one file", "shiftExif.failed.1");
				}
				else
				{
					title = NSLocalizedString(@"ShiftFile failed on one file", "shiftFile.failed.1");
				}
			}
			else
			{
				NSString *msg;
				if (YES == exif)
				{
					msg = NSLocalizedString(@"ShiftExif failed on %d files", @"shiftExif.failed.>1");
				}
				else
				{
					msg = NSLocalizedString(@"ShiftFile failed on %d files", @"shiftFile.failed.>1");
				}
				title = [NSString stringWithFormat: msg, countFailed];
			}

			NSString *temp;
			if (YES == exif)
			{
				temp = NSLocalizedString(@"The following files failed: ", @"shiftExif.failed.list");
			}
			else
			{
				temp = NSLocalizedString(@"The following files failed: ", @"shiftFile.failed.list");
			}

			NSMutableString *msg = [NSMutableString stringWithFormat: temp];
			int idx;
			for (idx = 0; idx < countFailed; ++idx)
			{
				ThumbData *td = [failed objectAtIndex: idx];
				[msg appendString: [td name]];
				if (idx < (countFailed - 1))
				{
					[msg appendString: @", "];
				}
			}

			NSRunAlertPanel(title, msg, NSLocalizedString(@"Close", @"Close"), nil, nil);
		}

		[failed release];
	}
}

//------------------------------------------------------------------------------
- (void) shiftExifDate:(NSArray*) tdList
{
	if ([tdList count] < 1)
	{
		NSLog(@"shiftExifDate called with empty list");
		return;
	}

	[self shiftHelper: tdList  exif:YES];
}

//------------------------------------------------------------------------------
- (void) shiftFileDate:(NSArray*) tdList
{
	if ([tdList count] < 1)
	{
		NSLog(@"shiftFileDate called with empty list");
		return;
	}

	[self shiftHelper: tdList  exif:NO];
}

//------------------------------------------------------------------------------
- (void) setToExifDate:(NSArray *) tdList
{
	NSFileManager *fileManager = [NSFileManager defaultManager];

	int count = [tdList count];
	int idx;
	for (idx = 0; idx < count; ++idx)
	{
		ThumbData *td = [tdList objectAtIndex: idx];
		if (NO == [td doDatesMatch])
		{
			NSDictionary *oldAttrs = [fileManager fileAttributesAtPath: [td fullPath] traverseLink: NO];
			NSMutableDictionary *newAttrs = [NSMutableDictionary dictionaryWithDictionary: oldAttrs];
			NSDate *exifDate = [td exifDate];
			if (nil != exifDate)
			{
				[newAttrs setValue:exifDate  forKey:NSFileCreationDate];
				[newAttrs setValue:exifDate  forKey:NSFileModificationDate];
				[fileManager changeFileAttributes:newAttrs  atPath:[td fullPath]];
			}
		}
	}
}

//------------------------------------------------------------------------------
- (NSString*) stringFromErrorCode:(int) error
{
	return [NSString stringWithFormat: NSLocalizedString(@"Error code: %d", @"Error.code"), error];
}

//------------------------------------------------------------------------------
- (NSSound *) trashSound
{
	return soundToTrash;
}

//------------------------------------------------------------------------------
- (NSUserDefaults*) userPreferences
{
	return userPreferences;
}

//------------------------------------------------------------------------------
- (void) browserClosing:(PhotoBrowser*) pb
{
	[browsers removeObject: pb];
}

//------------------------------------------------------------------------------
- (void) slideshowClosing:(PhotoSlideShow*) ps
{
	[slideshows removeObject: ps];
}

//------------------------------------------------------------------------------
- (void) viewerClosing:(PhotoViewer*) pv
{
	[viewers removeObject: pv];
}

//------------------------------------------------------------------------------
// Some special handling of various menu items
- (void) updateSpecialMenus:(NSMenuItem*) menuItem
{
	id bv = [self activeBrowserOrViewer];
	int sort = [bv sortBy];
	if (menuItem == menuSortByDates)
	{
		[menuItem setState: SORT_BY_DATE == sort];
	}
	else
	if (menuItem == menuSortByNames)
	{
		[menuItem setState: SORT_BY_NAME == sort];
	}
	else
	if (menuItem == menuSortByTypes)
	{
		[menuItem setState: SORT_BY_TYPE == sort];
	}
	else
	if (menuItem == menuSortByThumbs)
	{
		[menuItem setState: SORT_BY_THUMBSTATE == sort];
	}
}

//------------------------------------------------------------------------------
// Private helpers
//------------------------------------------------------------------------------
- (BOOL) validateMenuItem:(id <NSMenuItem>) menuItem
{
	BOOL enabled = NO;

	id bv = nil;
	switch ([menuItem tag])
	{
		case MN_TAG_ALWAYS:
			enabled = YES;
			break;
		case MN_TAG_PATH:
			bv = [self activeBrowserOrViewer];
			enabled = [bv hasDirectory];
			break;
		case MN_TAG_IMAGE:
			bv = [self activeBrowserOrViewer];
			enabled = [bv hasSelectedImage];
			break;
		case MN_TAG_JPEG:
			bv = [self activeBrowserOrViewer];
			enabled = [bv hasSelectedJPEG];
			break;
	}

	return enabled;
}

//------------------------------------------------------------------------------
- (id) activeBrowserOrViewer
{
	NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow];
	return [keyWindow delegate];
}

//------------------------------------------------------------------------------
- (PhotoBrowser*) createBrowser
{
	PhotoBrowser *pb = [[PhotoBrowser alloc] init];
	[browsers addObject: pb];
	[pb release];
	[NSBundle loadNibNamed:@"PhotoBrowser"  owner:pb];

	NSString *val = [userPreferences stringForKey: PREF_BROWSER_FRAME_RECT];
	if (nil != val)
	{
		NSRect frame = NSRectFromString(val);
		[[pb mainWindow] setFrame: frame display:YES];
	}

	int count = [browsers count] - 1;
	if (count > 0)
	{
		count = count % 6;
		NSRect rect = [[pb mainWindow] frame];
		rect.origin.x += count * 10;
		rect.origin.y -= count * 10;
		[[pb mainWindow] setFrame:rect display:YES];
	}

	[[pb mainWindow] makeKeyAndOrderFront: [pb mainWindow]];
	return pb;
}

//------------------------------------------------------------------------------
- (PhotoSlideShow*) createSlideshow:(BOOL) show
{
	PhotoSlideShow *ps = [[PhotoSlideShow alloc] init];
	[slideshows addObject: ps];
	[ps release];

	[NSBundle loadNibNamed:@"PhotoViewer"  owner:ps];

	if (YES == show)
	{
		NSString *val = [userPreferences stringForKey: PREF_SLIDESHOW_FRAME_RECT];
		if (nil != val)
		{
			NSRect frame = NSRectFromString(val);
			[[ps mainWindow] setFrame: frame display:YES];
		}

		int count = [slideshows count] - 1;
		if (count > 0)
		{
			count = count % 6;
			NSRect rect = [[ps mainWindow] frame];
			rect.origin.x += count * 10;
			rect.origin.y -= count * 10;
			[[ps mainWindow] setFrame:rect display:YES];
		}

		[[ps mainWindow] makeKeyAndOrderFront: [ps mainWindow]];
	}

	return ps;
}

//------------------------------------------------------------------------------
- (PhotoViewer*) createViewer
{
	if (YES == [[self preferencesData] useSingleWindow])
	{
		if ([viewers count] > 0)
		{
			PhotoViewer *pv = [viewers objectAtIndex: 0];
			[[pv mainWindow] makeKeyAndOrderFront: [pv mainWindow]];
			return pv;
		}
	}

	PhotoViewer *pv = [[PhotoViewer alloc] init];
	[viewers addObject: pv];
	[pv release];

	[NSBundle loadNibNamed:@"PhotoViewer"  owner:pv];

	NSString *val = [userPreferences stringForKey: PREF_VIEWER_FRAME_RECT];
	if (nil != val)
	{
		NSRect frame = NSRectFromString(val);
		[[pv mainWindow] setFrame: frame display:YES];
	}

	int count = [viewers count] - 1;
	if (count > 0)
	{
		count = count % 6;
		NSRect rect = [[pv mainWindow] frame];
		rect.origin.x += count * 10;
		rect.origin.y -= count * 10;
		[[pv mainWindow] setFrame:rect display:YES];
	}

	[[pv mainWindow] makeKeyAndOrderFront: [pv mainWindow]];

	return pv;
}

//------------------------------------------------------------------------------
- (PhotoBrowser*) getOrCreateBrowser
{
	PhotoBrowser *pb = [self activeBrowserOrViewer];
	if (nil == pb ||
		NO == [pb isKindOfClass: [PhotoBrowser class]])
	{
		pb = [self createBrowser];
	}

	return pb;
}

//------------------------------------------------------------------------------
- (PhotoViewer*) openImageInViewer:(NSString*) file
{
	PhotoViewer *pv = [self createViewer];
	[pv openImageFile: file  showImage:YES];
	return pv;
}

//------------------------------------------------------------------------------
- (PhotoSlideShow*) startAutoSlideshow:(NSString *) folderName
{
	SlideshowModel *ssModel = [[SlideshowModel alloc] initWithDirectory
		:folderName  
		name:@"Auto" 
		incSub:YES];
	[ssModel setDuration: [prefsData slideshowDelay]];
	return [self openSlideshow: ssModel  show:YES];
}

//------------------------------------------------------------------------------
- (PhotoSlideShow*) openSlideshowFile:(NSString*) filename
{
	SlideshowModel *ssModel = [[SlideshowModel alloc] initWithFile: filename];
	if (nil == ssModel)
	{
		NSString *msg = NSLocalizedString(@"Unable to open slideshow file \"%@\"", @"openBadSlideshowMsg");
		NSRunAlertPanel(
			NSLocalizedString(@"Unsupported slideshow", @"openUnsupportedSlideshowTitle"),
			[NSString stringWithFormat: msg, filename],
			NSLocalizedString(@"OK", @"OK"),
			nil,
			nil);
		return nil;
	}

	return [self openSlideshow: ssModel  show:YES];
}

//------------------------------------------------------------------------------
- (PhotoSlideShow*) openSlideshow:(SlideshowModel*) model  show:(BOOL)show
{
	PhotoSlideShow *ps = [self createSlideshow: show];
	[ps setModel: model  start:YES];
	return ps;
}

//------------------------------------------------------------------------------
- (void) manageSlideshows
{
	if (nil == ssManager)
	{
		ssManager = [[SlideshowManager alloc] init];
		[NSBundle loadNibNamed:@"SlideshowManager"  owner:ssManager];

		NSString *val = [userPreferences stringForKey: PREF_SLIDESHOW_MANAGER_FRAME_RECT];
		if (nil != val)
		{
			NSRect frame = NSRectFromString(val);
			[[ssManager mainWindow] setFrame: frame display:YES];
		}
	}

	[[ssManager mainWindow] makeKeyAndOrderFront: [ssManager mainWindow]];
}

//------------------------------------------------------------------------------
- (void) slideshowManagerClosing
{
	ssManager = nil;
}

//------------------------------------------------------------------------------
- (BOOL) isSupportedFile:(NSString*) filename
{
	NSString *ext = [[filename pathExtension] lowercaseString];
	return 0 != [ext length] && NSNotFound != [fileTypes indexOfObject: ext];
}

//------------------------------------------------------------------------------
- (BOOL) isSlideshowFile:(NSString*) filename
{
	NSString *ext = [[filename pathExtension] lowercaseString];
	return 0 != [ext length] && NSOrderedSame == [ext caseInsensitiveCompare: @"slideshow"];
}

//------------------------------------------------------------------------------
- (void) filterImageFiles:(NSMutableArray*) allFiles
{
	int count = [allFiles count];
	int idx;
	for (idx = count - 1; idx >= 0; --idx)
	{
		NSString *filename = [allFiles objectAtIndex: idx];
		if (NO == [self isSupportedFile: filename])
		{
			[allFiles removeObjectAtIndex: idx];
		}
	}
}

//------------------------------------------------------------------------------
- (PreferencesData*) preferencesData
{
	return prefsData;
}

//------------------------------------------------------------------------------
- (NSString*) lastMoveOrCopyFolder
{
	return lastMoveOrCopyFolder;
}

//------------------------------------------------------------------------------
- (void) setLastMoveOrCopyFolder:(NSString*)newFolder
{
	[lastMoveOrCopyFolder release];

	lastMoveOrCopyFolder = newFolder;
	[lastMoveOrCopyFolder retain];
}

//------------------------------------------------------------------------------
- (NSMenu*) imageMenu
{
	return imageMenu;
}

//------------------------------------------------------------------------------
- (NSMenu*) directoryMenu
{
	return directoryMenu;
}

//------------------------------------------------------------------------------
- (NSDragOperation) draggingEnteredHelper:(id <NSDraggingInfo>) sender
{
	if (nil == [sender draggingSource])
	{
		return NSDragOperationGeneric;
	}

	return NSDragOperationNone;
}

//------------------------------------------------------------------------------
- (BOOL) prepareForDragOperationHelper:(id <NSDraggingInfo>) sender
{
	if (nil == [sender draggingSource])
	{
		return YES;
	}

	return NO;
}

//------------------------------------------------------------------------------
- (BOOL) performDragOperationHelper:(id <NSDraggingInfo>) sender
{
	if (nil == [sender draggingSource])
	{
		NSPasteboard *pb = [sender draggingPasteboard];
		if ([[pb types] containsObject: NSFilenamesPboardType])
		{
			NSArray *files = [pb propertyListForType: NSFilenamesPboardType];
			// We only handle the first file
			if ([files count] > 0)
			{
				NSString *path = [files objectAtIndex: 0];
				if (nil != path)
				{
					[self application:NSApp  openFile: path];
					return YES;
				}
			}
		}
	}

	return NO;
}


@end
